import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtForm ,AtInput, AtIcon } from 'taro-ui'

import './login.scss'
import {api_login} from '../../../utils/api.jsx'

export default class Login extends Component {

  constructor(props){
    super(props);
    this.state = {
      phone:'',
      password:'',
      is_phone_correct:false,
      flag:'password'       // 是否显示密码
    }
  }

  toUserCenter = () => {
    Taro.reLaunch({url: '/pages/userCenter/userCenter'})
  }

  toBindPhone = () => {
    Taro.showModal({
      title: 'Tip',
      content: '您的手机号尚未注册!前往注册',
      cancelText:'取消',
      confirmText:'确认',
      success: function (res) {
        if (res.confirm) {
          Taro.navigateTo({url: '/pages/pagesB/bindPhone/bindPhone'})
        } else if (res.cancel) {

        }
      }
    })
  }

  isShowPwd = () => {
    if(this.state.flag == 'password'){
      this.setState({flag:'text'})
    }else{
      this.setState({flag:'password'})
    }

  }

  // 发送数据并请求结果
  request = async () => {    
    const params = {
      url: api_login,
      cache:'reload',
      data: {
        phone:this.state.phone,
        password:this.state.password
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {Taro.setStorageSync('loginInfo',res.data)},
      fail: (res) => {console.log(res.data)}
    }
    
    var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(this.state.phone)) {
      // 手机号格式错误时，直接返回，不会发送数据
      if(this.state.phone.length == 0){
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
      }else{
        Taro.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 2000
        })
      } 
    }else if(this.state.password.length == 0){
      Taro.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
    }else{
      await Taro.request(params)
      const result = Taro.getStorageSync('loginInfo')
      const is_phone_exist = result[0]
      const is_password_correct = result[1]
      // 当手机号格式正确且数据库没有的时候，显示注册引导的模态框
      if(!is_phone_exist){
        this.toBindPhone()
      }else if(!is_password_correct){
        Taro.showToast({
          title: '密码错误',
          icon: 'none',
          duration: 2000
        })
      }else{
        // 手机号与密码都验证正确后重定向到用户中心
        Taro.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1000
        })
        // 登录成功后设置缓存，记录其登录状态
        Taro.setStorage({
          key:"userInfo",
          data:{
            userPhone:this.state.phone,
            isLogin:true
          }
        })
        Taro.setStorage({
          key:"bindFlag",
          data:{
            bindFlag:false
          }
        })
        setTimeout(this.toUserCenter,1000)
      }
    }
  }

  render () {
    return (
      <View>
        <AtForm>
          <AtInput className='phone'
            name='phone'
            border={true}
            title=''
            type='phone'
            required='true'
            placeholder='请输入手机号码'
            value={this.state.phone}
            onChange={(e) =>this.setState({phone:e})}
          >
          </AtInput>
          <AtInput className='password'
            name='password'
            title=''
            type={this.state.flag}
            required='true'
            border='true'
            placeholder='请输入密码'
            value={this.state.password}
            onChange={(e) =>this.setState({password:e})}
          >
            <AtIcon value='eye' className='showPwd' size='20' color='#999'
            onClick={this.isShowPwd}
            ></AtIcon>
          </AtInput>
          <button className='verifyBtn' onClick={this.request} type='primary'>确定</button>
        </AtForm>
        {/* 引导登录 */}
        <view>
          <text className='tipBindPhone' 
            onClick={() =>Taro.navigateTo({url: '/pages/pagesB/bindPhone/bindPhone'})}>
            注册
          </text>
          <text className='tipResetPwd'
            onClick={() =>Taro.navigateTo({url: '/pages/pagesB/resetPwd/resetPwd'})}>
            忘记密码
          </text>
        </view>
      </View>
    )
  }
}